package com.example.dbcms.aspect;


import com.example.dbcms.annotation.Log;
import com.example.dbcms.domain.User;
import com.example.dbcms.service.UserService;
import com.example.dbcms.utils.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 日志记录访问数据操作处理
 *
 * @author chenglong
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private UserService userService;

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    // 配置织入点
    @Pointcut("@annotation(com.example.dbcms.annotation.Log)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后处理
     *
     * @param joinPoint
     * @param jsonResult
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {

        // 获得注解
        Log controllerLog = null;
        try {
            controllerLog = getAnnotationLog(joinPoint);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (controllerLog == null) {
            return;
        } else {
            //获取当前用户
            String userAccount = (String) SecurityUtils.getSubject().getPrincipal();//获得账号
            User user = userService.getUserByUserAccount(userAccount);
            //System.out.println("用户:(id-" +user.getUserCount()+")"+ user.getUsername() + "在" + DateUtil.getCurrentDate() + "请求调用" + controllerLog.type());
            log.info("用户:(id-" +user.getUserCount()+")"+ user.getUsername() + "在" + DateUtil.getCurrentDate() + "请求调用" + controllerLog.type());
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }


}
